package com.jwsoft.manager.core.integration.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.data.core.util.PagerUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.vo.eduBusiEnrollOrder.EduBusiEnrollOrderQueryVO;
import com.jwsoft.manager.common.vo.eduHousehold.EduHouseholdVO;
import com.jwsoft.manager.common.vo.eduHouseholdOffline.EduHouseholdOfflineVO;
import com.jwsoft.manager.common.vo.eduLivePlace.EduLivePlaceVO;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.service.EduLivePlaceService;
import com.jwsoft.manager.core.dao.service.EduStudentEnrollPreService;
import com.jwsoft.manager.core.integration.EduBusiEnrollOrderIntegration;
import com.jwsoft.manager.core.integration.EduLivePlaceIntegration;
import com.jwsoft.manager.core.util.EduEnrollClearCacheHelper;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.convert.Convert;
import java.util.List;
import com.bifang.engine.assistant.core.exception.AppException;
import org.springframework.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.jwsoft.manager.common.vo.eduLivePlaceOffline.EduLivePlaceOfflineVO;
import com.jwsoft.manager.common.vo.eduLivePlaceOffline.EduLivePlaceOfflineKeyVO;
import com.jwsoft.manager.common.vo.eduLivePlaceOffline.EduLivePlaceOfflineQueryVO;
import com.jwsoft.manager.core.integration.EduLivePlaceOfflineIntegration;
import com.jwsoft.manager.core.dao.service.EduLivePlaceOfflineService;

/**
 * 线下居住证新增业务实现类
 *
 * @author wangt
 * @since 2024-06-06
 */
@ApiService(funcCode = "eduLivePlaceOffline", title = "线下居住证新增")
public class EduLivePlaceOfflineIntegrationImpl implements EduLivePlaceOfflineIntegration {

    @Autowired
    public EduLivePlaceOfflineService eduLivePlaceOfflineService;

    @Autowired
    private EduHelper eduHelper;

    @Autowired
    private EduLivePlaceService eduLivePlaceService;

    @Autowired
    private EduStudentEnrollPreService eduStudentEnrollPreService;

    @Autowired
    private EduEnrollClearCacheHelper eduEnrollClearCacheHelper;

    @Override
    @OpApi(funcCode = "eduLivePlaceOffline0001", title = "线下居住证新增分页查询", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public PageInfo<EduLivePlaceOfflineVO> getList(EduLivePlaceOfflineQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        if (vo.getYear()==null){
            vo.setYear(eduHelper.thisYear());
        }
        QueryWrapper<EduLivePlaceOffline> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StringUtils.isNotBlank(vo.getAuthStatus()),EduLivePlaceOffline::getAuthStatus,vo.getAuthStatus())
                .eq(vo.getYear()!=null,EduLivePlaceOffline::getYear,vo.getYear())
                .eq(StringUtils.isNotBlank(vo.getSfzh()),EduLivePlaceOffline::getSfzh,vo.getSfzh());

        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        List<EduLivePlaceOffline> list = eduLivePlaceOfflineService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduLivePlaceOffline> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduLivePlaceOfflineVO> resultList = Convert.toList(EduLivePlaceOfflineVO.class, pageInfo.getList());
        // 转义数据字典值
        // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduLivePlaceOffline0002", title = "线下居住证新增根据主键查询详情", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public EduLivePlaceOfflineVO getById(EduLivePlaceOfflineKeyVO vo) {
        EduLivePlaceOffline entity = eduLivePlaceOfflineService.getById(vo.getLivePlaceId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduLivePlaceOfflineVO result = Convert.convert(EduLivePlaceOfflineVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduLivePlaceOffline0003", title = "线下居住证新增保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduLivePlaceOfflineVO vo) {
        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduLivePlaceOffline0004", title = "线下居住证新增新增", funcType = FuncTypeEnum.insert,publicFlag = BoolEnum.TRUE)
    @SaveOplog(
            operationType = "eduLivePlaceOffline0004",
            operationName = "线下居住证新增新增",
            dataType = "livePlaceId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduLivePlaceOfflineVO add(EduLivePlaceOfflineVO vo) {
        Integer year = eduHelper.thisYear();
        vo.setYear(year);
        //保存前校验
        checkSave(vo);

        QueryWrapper<EduLivePlace> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduLivePlace::getSfzh,vo.getIdcard())
                .eq(EduLivePlace::getYear,vo.getYear());
        List<EduLivePlace> enrollPreList = eduLivePlaceService.list(queryWrapper);
        if(!CollectionUtils.isEmpty(enrollPreList)){
            vo.setLivePlaceId(enrollPreList.get(0).getLivePlaceId());
        }

        QueryWrapper<EduLivePlaceOffline> queryWrapperOffline = new QueryWrapper<>();
        queryWrapperOffline.lambda().eq(EduLivePlaceOffline::getSfzh,vo.getIdcard())
                .ne(EduLivePlaceOffline::getAuthStatus,AuthStatusEnum.NO.getType())
                .eq(EduLivePlaceOffline::getYear,vo.getYear());
        List<EduLivePlaceOffline> enrollPreOfflineList = eduLivePlaceOfflineService.list(queryWrapperOffline);
        if(!CollectionUtils.isEmpty(enrollPreOfflineList)){
            if (AuthStatusEnum.NODO.getType().equals(enrollPreOfflineList.get(0).getAuthStatus())){
                throw new AppException(vo.getIdcard()+"该身份证已办理线下居住证登记，等待工作人员审核，可前往“我的-当年适龄子女-居住中查看审核结果”！");
            }else{
                throw new AppException(vo.getIdcard()+"该身份证已办理线下居住证登记，已审核通过，可前往报名！");
            }

        }

        if(StringUtils.isNotBlank(vo.getQzrq())){
            vo.setQzrq(vo.getQzrq().replace("-",""));
        }
        if(StringUtils.isNotBlank(vo.getQzdqrq())){
            vo.setQzdqrq(vo.getQzdqrq().replace("-",""));
        }



        vo.setAuthStatus(AuthStatusEnum.NODO.getType());
        vo.setZjzt("正常");

        //保存数据
        EduLivePlaceOffline entity = Convert.convert(EduLivePlaceOffline.class, vo);
        eduLivePlaceOfflineService.saveOrUpdate(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setLivePlaceId(entity.getLivePlaceId());
        clearCache(entity.getSfzh());

        return vo;
    }

    @Override
    @OpApi(funcCode = "eduLivePlaceOffline0005", title = "线下居住证新增修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduLivePlaceOffline0005",
            operationName = "线下居住证新增修改",
            dataType = "livePlaceId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduLivePlaceOfflineVO edit(EduLivePlaceOfflineVO vo) {
        if (ObjectUtils.isEmpty(vo.getLivePlaceId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduLivePlaceOffline oldEntity = eduLivePlaceOfflineService.getById(vo.getLivePlaceId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduLivePlaceOffline entity = Convert.convert(EduLivePlaceOffline.class, vo);
        eduLivePlaceOfflineService.updateById(entity);
        clearCache(entity.getSfzh());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduLivePlaceOffline0006", title = "线下居住证新增根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduLivePlaceOffline0006",
            operationName = "线下居住证新增删除",
            dataType = "livePlaceId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduLivePlaceOfflineKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getLivePlaceId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduLivePlaceOffline entity = eduLivePlaceOfflineService.getById(vo.getLivePlaceId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduLivePlaceOfflineService.removeById(vo.getLivePlaceId());
        clearCache(entity.getSfzh());
    }

    @Override
    @OpApi(funcCode = "eduLivePlaceOffline0010", title = "线下居住证登记保存", funcType = FuncTypeEnum.edit,checkPrivilege = BoolEnum.FALSE)
    @SaveOplog(
            operationType = "eduLivePlaceOffline0010",
            operationName = "线下居住证登记保存",
            dataType = "livePlaceId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void saveOffline(EduLivePlaceOfflineVO vo) {
        if (ObjectUtils.isEmpty(vo.getLivePlaceId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduLivePlaceOffline oldEntity = eduLivePlaceOfflineService.getById(vo.getLivePlaceId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }


        //保存数据
        oldEntity.setAuthStatus(vo.getAuthStatus());
        eduLivePlaceOfflineService.updateById(oldEntity);


        if(AuthStatusEnum.YES.getType().equals(vo.getAuthStatus())){
            EduLivePlace eduLivePlace = Convert.convert(EduLivePlace.class,oldEntity);
            eduLivePlaceService.saveOrUpdate(eduLivePlace);
        }
        clearCache(oldEntity.getSfzh());
    }

    //清除缓存
    private void clearCache(String idcard){
        //查询人员
        if(StringUtils.isBlank(idcard)){
            return;
        }

        QueryWrapper<EduStudentEnrollPre> queryPreWrapper=new QueryWrapper<>();
        queryPreWrapper.lambda().select(EduStudentEnrollPre::getStudentEnrollPreId,EduStudentEnrollPre::getIdcard,EduStudentEnrollPre::getFatherIdcard,EduStudentEnrollPre::getMotherIdcard)
                .eq(EduStudentEnrollPre::getYear,eduHelper.thisYear())
                .and( wrapper -> {
                    wrapper.eq(EduStudentEnrollPre::getIdcard, idcard)
                            .or()
                            .eq(EduStudentEnrollPre::getFatherIdcard, idcard)
                            .or()
                            .eq(EduStudentEnrollPre::getMotherIdcard, idcard);
                });
        List<EduStudentEnrollPre> list=eduStudentEnrollPreService.list(queryPreWrapper);
        if (CollectionUtils.isEmpty(list)){
            return;
        }
        for (EduStudentEnrollPre pre:list) {
            //居住证
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreJzz(pre.getFatherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreJzz(pre.getMotherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreJzz(pre.getIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getFatherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getMotherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getIdcard());
            eduEnrollClearCacheHelper.clearCachePreBefore(pre.getStudentEnrollPreId());
        }
    }
}
